package com.pkk.penguin.frame.know.java.thread;

import cn.hutool.core.date.DatePattern;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.Test;

/**
 * @description: threadLocal的简单测试
 * @author: peikunkun
 * @create: 2020-08-14 17:32
 **/
public class ThreadLocalTests {

  public static ThreadLocal<SimpleDateFormat> THREADLOCAL = new ThreadLocal<SimpleDateFormat>() {
    /**
     * Returns the current thread's "initial value" for this thread-local variable.  This method will be
     * invoked the first time a thread accesses the variable with the {@link #get} method, unless the thread
     * previously invoked the {@link #set} method, in which case the {@code initialValue} method will not be
     * invoked for the thread.  Normally, this method is invoked at most once per thread, but it may be
     * invoked again in case of subsequent invocations of {@link #remove} followed by {@link #get}.
     *
     * <p>This implementation simply returns {@code null}; if the
     * programmer desires thread-local variables to have an initial value other than {@code null}, {@code
     * ThreadLocal} must be subclassed, and this method overridden.  Typically, an anonymous inner class will
     * be used.
     *
     * @return the initial value for this thread-local
     */
    @Override
    protected SimpleDateFormat initialValue() {
      return new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
    }
  };

  private static final ExecutorService executorService = Executors.newFixedThreadPool(100);


  @Test
  public void Administrator_11_20200814173313_() throws InterruptedException {
    System.out.println("欢迎使用单元测试方法【Administrator_11()_20200814173313】");
    System.out.println("此方法测试描述：【ThreadLocal的简单实用】");

    for (int i = 0; i < 300000; i++) {
      int j = i;
      executorService.execute(() -> {
        final SimpleDateFormat simpleDateFormat = THREADLOCAL.get();
        System.out.println(simpleDateFormat.format(new Date()));
      });
    }
    executorService.shutdown();
    executorService.awaitTermination(60L, TimeUnit.SECONDS);


  }

}
